 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=197 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:01 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Use boxing with care
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='auto&#045;box,auto&#045;unbox,autobox,autounbox,wrapper,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Use boxing with care</div>

<div class='main-body'>
 
<a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html">Boxing</a>
was introduced in JDK 1.5 to eliminate trivial conversions between primitives
(<tt>int</tt>, <tt>boolean</tt>, etc) and corresponding wrapper objects
(<tt>Integer</tt>, <tt>Boolean</tt>, etc). 
Boxing allows some code to be a bit more concise and legible.
It's also useful when using collections (which only take objects, not primitives). 

<p>There are two complimentary aspects of boxing :
<ul>
<li>auto-boxing, which refers to automatic conversion of an <tt>int</tt> to
an <tt>Integer</tt>, for example</li>
<li>auto-unboxing, which refers to automatic conversion of a <tt>Boolean</tt>
to a <tt>boolean</tt>, for example</li>
</ul>

<P>Boxing <em>partially hides</em> the distinction between primitives and corresponding wrapper objects, but it doesn't remove it. 
There are two distinctions which are not changed by boxing:
<ul>
 <li>objects can be <tt>null</tt>, while primitives cannot
 <li>objects have both state and identity, while primitives have only state (the value)
</ul>

Occasionally, these differences can cause problems when using boxing.

<p>Some points to remember :
<ul>
<li>be careful with <tt>null</tt>s. Auto-unboxing a <tt>null</tt> object will cause a <tt>NullPointerException</tt>.</li>
<li>comparing items with <tt>==</tt> and <tt>equals</tt> must be done with care.
</ul>

The rules for comparison of primitives and wrapper objects are as follows.

<p>If <tt>x</tt> and <tt>y</tt> are either both primitives, or both objects, then no boxing occurs :
<br>&nbsp;
<table BORDER CELLSPACING=0 CELLPADDING=3 COLS=3 WIDTH="75%" >
 <tr VALIGN=TOP>
  <td><b>Operation</b></td>
  <td><b><tt>Two primitives</b></td>
  <td><b><tt>Two objects</b></td>
 </tr>
 <tr>
  <td><tt>x == y</tt></td>
  <td>compare value</td>
  <td>compare identity</td>
 </tr>
 <tr>
  <td><tt>x.equals(y)</tt></td>
  <td>does not compile</td>
  <td>compare value</td>
 </tr>
</table>

<p>If one item is a primitive, and the other item is a <em>corresponding</em> wrapper object, then boxing can occur :
<br>&nbsp;
<table BORDER CELLSPACING=0 CELLPADDING=2 WIDTH="75%" >
 <tr VALIGN=TOP>
  <td><b>Operation</b></td>
  <td><b>Behavior</b></td>
 </tr>
 <tr>
  <td WIDTH="40%"><tt>x == y</tt></td>
  <td>treat as two primitives, and compare value</td>
 </tr>
 <tr>
  <td VALIGN=TOP nowrap><tt>x.equals(y)</tt></td>
  <td>does not compile if <tt>x</tt> is a primitive ; otherwise treat as two objects, and compare value</td>
 </tr>
</table>

<p><b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> BoxingExamples {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>final</span> <span class='keyword'>void</span> main(String... aArgs){
    <span class='comment'>//pass Integer where int expected
</span>    explode(<span class='keyword'>new</span> Integer(<span class='literal'>3</span>));

    <span class='comment'>//pass literal where Boolean expected
</span>    tellTruth(<span class='keyword'>true</span>);

    <span class='comment'>//calculate "int-erchangably" with int and Integer
</span>    Integer integerYear = <span class='keyword'>new</span> Integer(<span class='literal'>1989</span>);
    Integer otherIntegerYear = integerYear + <span class='literal'>10</span>;
    <span class='keyword'>int</span> intYear = integerYear + <span class='keyword'>new</span> Integer(<span class='literal'>15</span>);
    log(integerYear.toString());
    log(otherIntegerYear.toString());
    System.out.println(intYear);

    <span class='comment'>/*
    * Comparison of primitives and wrapper objects using == and equals.
    *
    * When both items are of the same type :
    *             2 primitives          2 objects
    * ----------------------------------------------------------
    * ==       :  value                 identity
    * equals() :  not applicable        value
    *
    *
    * When one item is a primitive, and the other is an object :
    * ==          :  treat as two primitives
    * x.equals(y) :  treat as two objects; do not compile if x is primitive
    */</span>
    intYear = <span class='literal'>1880</span>;
    integerYear = <span class='keyword'>new</span> Integer(<span class='literal'>1880</span>);
    <span class='keyword'>if</span> ( intYear == integerYear ){
      log(<span class='literal'>"intYear == integerYear: TRUE"</span>); <span class='comment'>// yes
</span>    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"intYear == integerYear : FALSE"</span>);
    }
    <span class='keyword'>if</span> ( integerYear.equals(intYear) ){
      log(<span class='literal'>"integerYear.equals(intYear): TRUE"</span>); <span class='comment'>//yes
</span>    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"integerYear.equals(intYear): FALSE"</span>);
    }
    <span class='comment'>//does not compile "int cannot be dereferenced" :
</span>    <span class='comment'>//intYear.equals(integerYear);
</span>
    intYear = <span class='literal'>1881</span>; <span class='comment'>//new value
</span>    <span class='keyword'>if</span> ( intYear == integerYear ){
      log(<span class='literal'>"intYear == integerYear: TRUE"</span>);
    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"intYear == integerYear : FALSE"</span>); <span class='comment'>// yes
</span>    }
    <span class='keyword'>if</span> ( integerYear.equals(intYear) ){
      log(<span class='literal'>"integerYear.equals(intYear): TRUE"</span>);
    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"integerYear.equals(intYear): FALSE"</span>); <span class='comment'>//yes
</span>    }
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> explode(<span class='keyword'>int</span> aNumTimes){
    log(<span class='literal'>"Exploding "</span> + aNumTimes + <span class='literal'>" times."</span>);
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> tellTruth(Boolean aChoice){
    <span class='comment'>//instead of if ( aChoice.booleanValue() ) {
</span>    <span class='keyword'>if</span> ( aChoice ) {
      log(<span class='literal'>"Telling truth."</span>);
    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"Lying like a rug."</span>);
    }
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(String aText){
    System.out.println(aText);
  }
}
 
</PRE>
<br>
<br>An example run of this class :
<p><tt>>java -classpath . BoxingExamples</tt>
<br><tt>Exploding 3 times.</tt>
<br><tt>Telling truth.</tt>
<br><tt>1989</tt>
<br><tt>1999</tt>
<br><tt>2004</tt>
<br><tt>intYear == integerYear: TRUE</tt>
<br><tt>integerYear.equals(intYear): TRUE</tt>
<br><tt>intYear == integerYear : FALSE</tt>
<br><tt>integerYear.equals(intYear): FALSE</tt>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction1deb-2.html?Id=17'>Implementing equals</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='197'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=197 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:01 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
